package com.woniu.smart.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.smart.entity.SysPermission;
import com.woniu.smart.util.JwtUtils;
import com.woniu.smart.util.RedisCache;
import com.woniu.smart.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author: WangHeng
 * @Date: 2022/10/24 21:49
 */
public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisCache redisCache;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //存放authentication到SecurityContextHolder，后续security就能获取到当前登录的用户信息了
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //得到认证成功后的对象信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String username = loginUser.getUsername();
        //通过账户名生成token
        String token = jwtUtils.generateToken(username);
        redisCache.setCacheObject("rbac"+username,loginUser,10, TimeUnit.HOURS);
        List<SysPermission> permissions = loginUser.getSysPermissions();
        String string = new ObjectMapper().writeValueAsString(Result.ok().data("menuList", permissions).data("token",token));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(string);
    }
}
